
/**
 * @function formatJSON
 * @description 格式化JSON
 */
export function formatJSON<T extends Record<string, any>>(array: T[], key: string) {
  return array.filter((item) => {
    if (item.hasOwnProperty(key) && item[key]) {
      item[key as keyof T] = item[key].split(',');
    }

    return item;
  });
}

/**
 * @function jsonToArr
 * @description JSON 字符串转数组
 */
export function jsonToArr<T extends Record<string, any>>(str: string): T[] {
  return JSON.parse(str);
}

/**
 * @function strToArr
 * @description 字符串转数组
 */
export function strToArr(str: string) {
  return str.split(',');
}

/**
 * @function replaceToSpace
 * @description 替换逗号为空格
 */
export function replaceToSpace(str: string) {
  return str.replace(/,/g, ' ');
}

/**
 * @function trimSpace
 * @description 去除字符串中的空格
 */
export function trimSpace(str: string) {
  return str.replace(/\s+/g, '');
}

/**
 * @function throttle
 * @description 节流函数
 */
export function throttle<T extends ((...args: any[]) => void)>(this: any, fn: T, delay: number) {
  let timer: NodeJS.Timeout | null = null;
  let beginTime = new Date().getTime();
  const ctx = this;
  const delayTime = typeof delay === 'number' && delay > 500 ? delay : 500;

  return function (...args: Parameters<T>) {
    let currentTime = new Date().getTime();

    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    if (currentTime - beginTime >= delayTime) {
      fn.apply(ctx, args);
      beginTime = currentTime;
    } else {
      timer = setTimeout(() => {
        fn.apply(ctx, args);
      }, delayTime);
    }
  }
}
